package com.itheima.controller;

import cn.hutool.core.util.IdUtil;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.GetRandom;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

/**
 * @author Envy
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RedisTemplate<String, String> redisTemplate2;
    @Resource
    private UserService userService;

    /**
     * 发送短信
     */
    @PostMapping("/sendMsg")
    public R<Object> sendMsg(@RequestBody User user) {
        String phone = user.getPhone();
        String code = "1234";
        System.out.println("=====================================" + phone);
        redisTemplate2.opsForValue().set("phone", code);
        return R.success("发送成功");
    }

    /**
     * 短信验证登录
     */
    @PostMapping("/login")
    public R<Object> login(@RequestBody User user) {
        String phone = user.getPhone();
        String code = user.getCode();
        String code1 = redisTemplate2.opsForValue().get("phone");
        System.out.println("=============================="+code1);
        //对比验证码是否匹配
        if (code1.equals(code)) {
            //如果验证码正确就查询该用户是否注册
            User user1 = userService.selectUser(phone);
            //如果用户没有注册就给用户注册一个默认账户
            if (user1 == null) {
                //用时间戳生成用户默认id
                String id = IdUtil.getSnowflakeNextIdStr();
                user.setId(id);
                //设置默认用户名
                user.setName("新用户" + GetRandom.getFourRandom());
                //设置手机号
                user.setPhone(phone);
                redisTemplate.opsForValue().set("token", user);

                //将注册的默认用户添加到表中
                userService.addUser(user);
            }
            redisTemplate.opsForValue().set("token", user);
            //如果已经注册就直接返回
            return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * 登出功能
     */
    @PostMapping("/loginout")
    public R<String> loginout() {
        redisTemplate2.delete("phone");
        return R.success("退出成功");
    }
}
